package com.rose.springbootwebsocket.config;

import com.alibaba.fastjson.JSON;
import com.rose.springbootwebsocket.service.WebSocketTestService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint(value = "/websocket")
@Service    //此注解千万千万不要忘记，它的主要作用就是将这个监听器纳入到Spring容器中进行管理
public class WebSocket {
    Logger logger = LoggerFactory.getLogger(getClass());
    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<WebSocket>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;
    //获取上下文对象
    private static ApplicationContext applicationContext;

    public static void setApplicationContext(ApplicationContext applicationContext) {
        WebSocket.applicationContext = applicationContext;
    }
    private WebSocketTestService webSocketTestService;
    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        webSocketTestService = applicationContext.getBean(WebSocketTestService.class);
        this.session = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        logger.info("有新连接加入！当前连接数为" + getOnlineCount());
        WebSocketResponse.sendSuccess("欢迎使用webSocket执行解析。。");
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
        logger.info("有一连接关闭！当前连接数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        logger.info("来自客户端的消息:" + message);
        try{
            WebSocketRequest request = JSON.parseObject(message, WebSocketRequest.class);
            Class<? extends WebSocketTestService> aClass = webSocketTestService.getClass();
            if (StringUtils.isEmpty(request.getMethod())){
                WebSocketResponse.sendDataError("解析方法不能为空",JSON.toJSONString(request));
                return;
            }
            Method method = aClass.getDeclaredMethod(request.getMethod(), WebSocketRequest.class);
            method.invoke(webSocketTestService,request);
        }catch(Exception e){
            WebSocketResponse.sendDataError(e,null);
        }
        WebSocketResponse.sendSuccess("解析完成");
    }

    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable error) {
        logger.info("发生错误");
        error.printStackTrace();
    }


    private void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    public static void sendInfo(WebSocketResponse response){
        sendInfo(JSON.toJSONString(response));
    }
    /**
     * 群发自定义消息
     */
    private static void sendInfo(String message){
        for (WebSocket item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (Exception e) {
                continue;
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocket.onlineCount--;
    }
}